package com.ego.servcie.impl;

import com.ego.dubbo.service.ItemCatDubboService;
import com.ego.dubbo.service.ItemDubboService;
import com.ego.pojo.*;
import com.ego.servcie.SearchService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Sort;
import org.springframework.data.solr.core.SolrTemplate;
import org.springframework.data.solr.core.query.Criteria;
import org.springframework.data.solr.core.query.HighlightOptions;
import org.springframework.data.solr.core.query.HighlightQuery;
import org.springframework.data.solr.core.query.SimpleHighlightQuery;
import org.springframework.data.solr.core.query.result.HighlightEntry;
import org.springframework.data.solr.core.query.result.HighlightPage;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class SearchServiceImpl implements SearchService {

    @DubboReference
    private ItemCatDubboService itemCatDubboService;

    @DubboReference
    private ItemDubboService itemDubboService;

    @Autowired
    private SolrTemplate solrTemplate;

    @Value("${ego.solr.core.name}")
    private String collection;

    @Override
    public Map<String, Object> searchItem(String query, int page, int rows) {
        // 设置搜索条件
        Criteria c = new Criteria("item_keywords");
        // 设置搜索内容
        c.is(query);
        HighlightQuery highlightQuery = new SimpleHighlightQuery(c);
        // 设置排序，按照上架时间进行排序。修改了商品或新增了商品，排在最前面。
        highlightQuery.addSort(Sort.by(Sort.Direction.DESC, "_version_"));
        // 设置分页
        // 设置从哪条开始查询
        highlightQuery.setOffset((long) rows * (page - 1));
        // 查询数量
        highlightQuery.setRows(rows);


        // 设置高亮
        HighlightOptions ops = new HighlightOptions();
        ops.addField("item_title", "item_sell_point");
        ops.setSimplePrefix("<span style='color:red'>");
        ops.setSimplePostfix("</span>");
        highlightQuery.setHighlightOptions(ops);

        // 执行查询，相当于点击了查询按钮
        HighlightPage<SearchPojo> highlightPage = solrTemplate.queryForHighlightPage("ego", highlightQuery, SearchPojo.class);

        // 获取到包含高亮数据的集合
        List<HighlightEntry<SearchPojo>> highlighted = highlightPage.getHighlighted();

        // 页面要的数据,作用域中需要itemList
        List<SearchPojo> list = new ArrayList<>();

        for (HighlightEntry<SearchPojo> highlightEntry : highlighted) {
            // 所有非高亮数据。solr响应时docs中的数据
            SearchPojo entity = highlightEntry.getEntity();
            // 把image转换为images
            String image = entity.getImage();
            entity.setImages(image != null && !image.equals("") ? image.split(",") : new String[1]);
            // 获取高亮数据，Solr响应中highlighting
            List<HighlightEntry.Highlight> listHL = highlightEntry.getHighlights();
            // 替换非高亮数据
            for (HighlightEntry.Highlight highlight : listHL) {
                // 发现高亮中有item_title属性，说明此属性有高亮数据。就要去把非高亮数据替换。
                if (highlight.getField().toString().equals("item_title")) {
                    entity.setTitle(highlight.getSnipplets().get(0));
                }
                if (highlight.getField().toString().equals("item_sell_point")) {
                    entity.setSellPoint(highlight.getSnipplets().get(0));
                }

            }
            list.add(entity);
        }
        // 作用域中所有值
        Map<String, Object> map = new HashMap<>();
        // 查询条件
        map.put("query", query);
        // 总页数
        map.put("totalPages", highlightPage.getTotalPages());
        // 当前页显示数据
        map.put("itemList", list);
        // 当前页数
        map.put("page", page);
        return map;
    }

    @Override
    public EgoResult itemInsert(SearchPojo searchPojo) {
        ItemCat itemCat = itemCatDubboService.selectItemCatById(Long.parseLong(searchPojo.getCategoryName()));
        searchPojo.setCategoryName(itemCat.getName());

        UpdateResponse updateResponse = solrTemplate.saveBean(collection, searchPojo);
        solrTemplate.commit(collection);

        if (updateResponse.getStatus() == 0) {
            return EgoResult.ok();
        }
        return EgoResult.error("同步solr索引库失败");
    }

    @Override
    public EgoResult itemDelete(String[] ids) {
        UpdateResponse updateResponse = solrTemplate.deleteByIds(collection, Arrays.asList(ids));
        solrTemplate.commit(collection);
        if (updateResponse.getStatus() == 0) {
            return EgoResult.ok();
        }
        return EgoResult.error("同步solr索引库失败");
    }

    @Override
    public EgoResult itemReshelf(Long[] ids) {
        List<SearchPojo> searchPojos = new ArrayList<>();
        for (Long id : ids) {
            SearchPojo searchPojo = new SearchPojo();
            Item item = itemDubboService.selectItemByItemId(id);
            ItemDesc itemDesc = itemDubboService.selectItemDescByItemId(id);
            ItemCat itemCat = itemCatDubboService.selectItemCatById(item.getCid());
            searchPojo.setId(item.getId() + "");
            searchPojo.setTitle(item.getTitle());
            searchPojo.setSellPoint(item.getSellPoint());
            searchPojo.setImage(item.getImage());
            searchPojo.setPrice(item.getPrice());
            searchPojo.setDesc(itemDesc.getItemDesc());
            searchPojo.setCategoryName(item.getCid() + "");
            searchPojos.add(searchPojo);
        }
        UpdateResponse updateResponse = solrTemplate.saveBean(collection, searchPojos);
        solrTemplate.commit(collection);
        if (updateResponse.getStatus() == 0) {
            return EgoResult.ok();
        }
        return EgoResult.error("同步solr索引库失败");
    }


}
